package test4_14.demo03;

import java.util.ArrayList;
import java.util.List;

/*
    利用多线程求解某范围素数,每个线程负责 1000范围：
    线程1找1-1000；
    线程 2 找 1001-2000;
    线程 3 找 2001-3000。

    编程程序将每个线程找到的素数集中
    打印。所有的素数输出完毕后，再输出素数的总数；
     */
public class Homework22_7 {

    private static final List<Integer> allList = new ArrayList<>();

    static class Judge implements Runnable {
        private int start;
        private int end;

        public Judge(int start, int end) {
            this.start = start;
            this.end = end;
        }

        public static boolean isPrime(int i) {
            if (i == 1 || i == 3) {
                return true;
            } else if (i == 2) {
                return false;
            }
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    return false;
                }
            }
            return true;
        }

        @Override
        public void run() {
            List<Integer> list = new ArrayList<>();

            for (int i = start; i <= end; i++) {
                if (isPrime(i) == true) {
                    list.add(i);
                }
            }

            synchronized (allList) {
                allList.addAll(list);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        System.out.println("开始执行");
        Thread thread1 = new Thread(new Homework22_7.Judge(1, 1000));
        Thread thread2 = new Thread(new Homework22_7.Judge(1001, 2000));
        Thread thread3 = new Thread(new Homework22_7.Judge(2001, 3000));

        thread1.start();
        thread2.start();
        thread3.start();

        thread1.join();
        thread2.join();
        thread3.join();

        System.out.println(allList);
        System.out.println(allList.size());

        System.out.println("执行结束");
    }
}




